/*
 * Copyright (c) 2010 All Inclusive Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.allinclusive.fw.spring;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
import org.springframework.web.context.ContextLoader;

/**
 * Springコンテキストを取得するためのクラス
 */
public class SpringContextLoader {
	
	/** デフォルトロケーション*/
	public static final String DEFAULT_LOCATION = "classpath*:com/googlecode/allinclusive/fw/spring/beanRefContext.xml";
	
	/** デフォルトファクトリーキー */
	public static final String DEFAULT_FACTORY_KEY = "context";
	
	/**
	 * Batch環境でSpring ApplicationContextを取得します。
	 * @return　Springコンテキスト
	 */
	public static ApplicationContext getCurrentApplicationContext() {
		return getCurrentApplicationContext(null);
	}

	/**
	 * Batch環境でSpring ApplicationContextを取得します
	 * @param selector
	 * @return Springコンテキスト
	 */
	public static ApplicationContext getCurrentApplicationContext(String selector) {
		String resourceLocation = selector;
		if (resourceLocation == null) {
			resourceLocation = DEFAULT_LOCATION;
		}
		
		BeanFactoryLocator factoryLocator = ContextSingletonBeanFactoryLocator.getInstance(resourceLocation);
		ApplicationContext context = (ApplicationContext) factoryLocator.useBeanFactory(DEFAULT_FACTORY_KEY).getFactory();
		
		return context;
	}
	
	/**
	 * Online環境でSpring ApplicationContextを取得します。
	 * @return　Springコンテキスト
	 */
	public static ApplicationContext getCurrentWebApplicationContext() {
		return ContextLoader.getCurrentWebApplicationContext();
	}
}
